package homework;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCP_EchoServer_Thread {
    private ServerSocket serverSocket;

    public TCP_EchoServer_Thread(int port) throws IOException{
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException{
        System.out.println("服务器启动");
        
        while (true){
            Socket socket = serverSocket.accept();
            Thread t = new Thread(()->{
               this.processConnection(socket); 
            });
        }
    }

    private void processConnection(Socket socket) {
        System.out.printf("[%s:%d]客户端上线\n",socket.getInetAddress().toString(),socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true){
                if (!scanner.hasNext()){
                    System.out.printf("[%s:%d]客户端下线\n",socket.getInetAddress().toString(),socket.getPort());
                    break;
                }
            }
            String request = scanner.next();
            String response = process(request);
            writer.println(response);
            writer.flush();
            System.out.printf("[%s:%d]req:%s resp:%s\n",socket.getInetAddress().toString(),socket.getPort(),request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCP_EchoServer_Thread serverThread = new TCP_EchoServer_Thread(9090);
        serverThread.start();
    }
}
